package com.lynn.springboot_demo.exception;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

/**
 * @author cl
 * @Date 2020/9/8 15:03
 * <p>
 * 全局异常处理器
 */
@CrossOrigin
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(Exception e, HttpServletRequest request) {
        //开发调试的时候可以在控制台打印堆栈异常信息
        e.printStackTrace();
        String s = JSONObject.toJSONString(e);
        //详细异常错误信息，定位到某一行,severe级别最高，严重错误
        log.error("=====具体异常信息日志:[{}]", s);
        //只打印异常信息，不定位到具体某一行
        log.error("=====简单异常信息日志:[{}]", e.getMessage());
        JSONObject object = new JSONObject();
        object.put("code", 0);
        object.put("desc", "程序异常");
        return JSONObject.toJSONString(object);
    }
}
